/*
 * @Author: hongbin
 * @Date: 2022-11-22 11:06:27
 * @LastEditors: hongbin
 * @LastEditTime: 2022-11-22 20:54:20
 * @Description:
 */
import { FC, useEffect, useRef } from "react";
import styled, { css } from "styled-components";
import { useAuth } from "../../../context/AuthProvide";
import { Message } from "./Friends";

interface IProps {
    msgs: Message[];
}

const MessageList: FC<IProps> = ({ msgs }) => {
    const ref = useRef<HTMLDivElement>(null);
    const { user } = useAuth();

    useEffect(() => {
        ref.current?.scrollTo(0, ref.current.scrollHeight);
    }, [msgs]);

    return (
        <Container ref={ref}>
            {msgs.map((msg) => (
                <MessageBar title={new Date(msg.date).toLocaleString()} self={user._id == msg.sender} key={msg.date}>
                    <span>{msg.content}</span>
                </MessageBar>
            ))}
        </Container>
    );
};

export default MessageList;

const MessageBar = styled.div<{ self: boolean }>`
    margin: 0.5vmax;
    display: flex;
    span {
        display: inline-block;
        padding: 0.2vmax 1vmax;
        border-radius: 1vmax;
        background: #ccc;
        font-size: 1.3vmax;
        max-width: 80%;
    }
    ${({ self }) =>
        self &&
        css`
            justify-content: flex-end;
            span {
                background: #0d8d2b;
                color: #fffae5;
            }
        `}
`;

const Container = styled.div`
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden scroll;
`;
